package dao

import (
	"flare-admin/config/nacos"

	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/redis/go-redis/v9"
	"github.com/sirupsen/logrus"
	"k8s.io/apimachinery/pkg/util/yaml"
)

var (
	RedisDao *RedisConn
)

type RedisConnConfig struct {
	Addr     string `json:"addr" mapstructure:"addr" yaml:"addr"`
	Password string `json:"password" mapstructure:"password" yaml:"password"`
}

type RedisConn struct {
	Client *redis.Client
}

func init() {
	config, err := nacos.NacosClient.GetConfig(vo.ConfigParam{DataId: "redis-conn", Group: "DEFAULT_GROUP"})
	if err != nil {
		panic(err) // redis连不上的话不允许启动这个服务
	}

	cfg := &RedisConnConfig{}
	err = yaml.Unmarshal([]byte(config), cfg)
	if err != nil {
		panic(err)
	}

	RedisDao = NewRedisConn(cfg.Addr, cfg.Password)
	logrus.Infof("Successfully connected to Redis at %s", cfg.Addr)

}

func NewRedisConn(addr string, password string) *RedisConn {
	client := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: password,
	})
	return &RedisConn{
		Client: client,
	}
}
